# coding: utf-8
import pinyin
from django.db import models
from django.utils import timezone
from core.tools.encryption import md5


class ChannelMenusManager(models.Manager):
    @property
    def base_menus(self):
        return [
            {"name": "邀请好友", "sign": "yaoqinghaoyou"},
            {"name": "新手必读", "sign": "xinshoubidu"},
            {"name": "我的订单", "sign": "wodedingdan"},
            {"name": "我的团队", "sign": "wodetuandui"},
            {"name": "团队贡献", "sign": "tuanduigongxian"},
            {"name": "专属客服", "sign": "zhuanshukefu"},
            {"name": "个人资料", "sign": "gerenziliao"},
            {"name": "推广图", "sign": "tuiguangtu"},
        ]

    def no_set_menus(self, channel):
        menus = self.base_menus
        set_menus = self.filter(channel=channel)
        set_menus_json = []
        for i in set_menus:
            set_menus_json.append({"name": i.name, "sign": i.sign})
        no_set_json = []
        for no_set in menus:
            if no_set not in set_menus_json:
                no_set_json.append(no_set)
        return no_set_json


class ChannelMenus(models.Model):
    """
    如果有渠道菜单关联关系就根据关系显示，
    如果没有此关系，给前端返回all 直接显示
    """
    channel = models.ForeignKey("Channel", verbose_name="渠道")
    name = models.CharField(max_length=32, verbose_name="菜单名称")
    sign = models.CharField(max_length=32, verbose_name="标识", db_index=True, blank=True)
    objects = ChannelMenusManager()

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        sign = pinyin.get(self.name, format='strip')
        self.sign = sign
        super(ChannelMenus, self).save()

    class Meta:
        verbose_name = "渠道菜单"
        verbose_name_plural = verbose_name


class ChannelManager(models.Manager):
    def filter_name(self, name):
        return self.filter(name__contains=name)

    def create_channel(self, **kwargs):
        data = dict()
        data["name"] = kwargs.get("name")
        data["tel"] = kwargs.get("tel")
        data["username"] = kwargs.get("username")
        data["is_show_cash"] = kwargs.get("is_show_cash")
        data["level_num"] = kwargs.get("level_num")
        data["banner_ad"] = kwargs.get("banner_ad")
        data["check_menus"] = kwargs.get("check_menus")
        return self.create(**data)


class Channel(models.Model):
    MenusOption = ((1, "不检查"), (2, "检查整改渠道"), (3, "只检查最后一个层级"))
    name = models.CharField(max_length=32, verbose_name="渠道名称")
    tel = models.CharField(max_length=32, verbose_name="电话", unique=True)
    username = models.CharField(max_length=32, verbose_name="联系人姓名")
    is_get_dsx = models.BooleanField(verbose_name="是否可以领取盗刷险", default=False)
    is_show_cash = models.BooleanField(verbose_name="是否展示佣金", default=True)
    show_declaration = models.BooleanField(verbose_name="是否显示声明", default=False)
    create_time = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    level_num = models.IntegerField(default=0, verbose_name="层级数")
    banner_ad = models.BooleanField(default=True, verbose_name="滚动条")
    check_menus = models.IntegerField(default=1, verbose_name="菜单检查", choices=MenusOption)
    callback = models.CharField(verbose_name="回调链接", blank=True, null=True, max_length=256)
    objects = ChannelManager()

    class Meta:
        verbose_name = "渠道表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

    def update_data(self, data):
        self.name = data.get("name")
        self.username = data.get("username")
        self.tel = data.get("tel")
        self.is_show_cash = data.get("is_show_cash")
        self.level_num = data.get("level_num")
        self.banner_ad = data.get("banner_ad")
        self.check_menus = data.get("check_menus")
        self.save()


class ChannelShareImg(models.Model):
    channel = models.ForeignKey("Channel", verbose_name="渠道")
    img = models.ImageField(verbose_name="分享图片", upload_to='channel/share/', blank=True, null=True)
    shared_img = models.ImageField(verbose_name="分享后的图片", upload_to="channel/shared/", blank=True, null=True)

    class Meta:
        verbose_name = "渠道分享图片"
        verbose_name_plural = verbose_name


class ChannelPopular(models.Model):
    channel = models.ForeignKey('Channel', verbose_name="渠道")
    img = models.ImageField(verbose_name="渠道", upload_to="channel/popular/")
    code_position = models.CharField(verbose_name="二维码位置", help_text="用括号(xx,xx)", max_length=16)
    code_size = models.CharField(verbose_name="二维码大小", help_text="用括号(xx,xx)", max_length=16)
    status = models.BooleanField(verbose_name="是否可以正常使用", default=True)

    class Meta:
        verbose_name = "渠道推广图片"
        verbose_name_plural = verbose_name


class ChannelProductManager(models.Manager):
    def create_new_product(self, channel, product):
        channel_product_obj, created = self.get_or_create(
            channel=channel,
            product_id=product,
        )
        if not created:
            channel_product_obj.status = True
            channel_product_obj.save()
        return channel_product_obj, created

    def get_channel_products(self, channel, status=None):
        # 此渠道已经有的产品
        data = self.filter(product__status=True)
        if isinstance(channel, Channel):
            data = data.filter(channel=channel)
        else:
            data = data.filter(channel_id=channel)
        if status is not None:
            data = data.filter(status=status)
        return data

    def get_products(self):
        """
        获取所有产品
        :return:
        """
        return self.filter(status=True, product__status=True)

    def difference_products(self, channel):
        """
        获取差集
        :param channel:
        :return:
        """
        data1 = self.get_products()
        data2 = self.get_channel_products(channel)
        data1.difference(data2)
        return data1


class ChannelProduct(models.Model):
    channel = models.ForeignKey("Channel", verbose_name="渠道", null=True, blank=True)
    product = models.ForeignKey("product.Product", verbose_name="产品", null=True, blank=True)
    sum_price = models.DecimalField(verbose_name="价格", help_text="如果是百分比请换算成小数",
                                    default=0, max_digits=8, decimal_places=4)
    status = models.BooleanField(verbose_name="上架", default=True, db_index=True)
    create_time = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    product_update_time = models.DateTimeField(auto_now=True, verbose_name="更新产品的时间")
    update_time = models.DateTimeField(default=timezone.now, verbose_name="价格变动的生效时间")
    objects = ChannelProductManager()

    class Meta:
        verbose_name = "渠道产品关系表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return "%s-%s" % (self.channel.name, self.product.name)


class SalesManManager(models.Manager):
    def create_account(self, channel, **kwargs):
        can_transfer = kwargs.get('can_transfer')
        password = kwargs.get('password')
        account = kwargs.get('account')
        return self.create(
            account=account,
            password=md5(md5(password)),
            show_alert=False,
            can_transfer=can_transfer,
            channel=channel,
        )


class SalesMan(models.Model):
    userType = ((1, "普通用户"), (2, "会员用户"), (3, "服务商"), (4, "优秀服务商"))
    user_type = models.IntegerField(verbose_name="用户类型", choices=userType, default=1)
    superuser = models.BooleanField(verbose_name="是否是最大管理员", default=False, db_index=True)
    account = models.CharField(verbose_name="账号", blank=True, null=True, db_index=True, max_length=16)
    password = models.CharField(verbose_name="密码", blank=True, null=True, max_length=80)
    is_seller = models.BooleanField(verbose_name="是否是商户", default=False)
    seller_name = models.CharField(verbose_name="商户名称", blank=True, null=True, max_length=32)
    get_dsx = models.BooleanField(verbose_name="是否领过盗刷险", default=False)
    card = models.CharField(verbose_name="身份证号", blank=True, null=True, max_length=18)
    num = models.IntegerField(verbose_name="团队人员", default=0)
    name = models.CharField(verbose_name="姓名", max_length=16, blank=True, null=True)
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    update_time = models.DateTimeField(verbose_name="更新时间", auto_now=True)
    tel = models.CharField(verbose_name="手机号", max_length=16, db_index=True, blank=True, null=True)
    card_num = models.CharField(verbose_name="银行卡号", max_length=32, db_index=True, blank=True, null=True)
    leader = models.ForeignKey('self', verbose_name="上级", blank=True, null=True)
    wx_user = models.OneToOneField('wchat.WxUserInfo', verbose_name="微信用户", blank=True, null=True, db_index=True)
    qr_code = models.FileField(verbose_name="用户的微信二维码", upload_to="wx/qr_code/", blank=True, null=True)
    # 二维码
    scene_qr_code = models.CharField(verbose_name="推广的二维码", blank=True, null=True, max_length=512)
    expire_time = models.DateTimeField(verbose_name="二维码有效期", blank=True, null=True)
    # 增加渠道
    channel = models.ForeignKey("Channel", verbose_name="渠道", blank=True, null=True)
    # 是否是可以提现
    can_transfer = models.BooleanField(default=True, db_index=True, verbose_name="可以提现")
    # 是否显示首页弹框
    show_alert = models.BooleanField(default=True, db_index=True, verbose_name="显示弹窗")
    objects = SalesManManager()

    class Meta:
        verbose_name = "用户信息"  # admin后台显示
        verbose_name_plural = verbose_name  # 复数显示

    def get_lower_list(self):
        """
        获取下两级的所有人
        :return:
        """
        all_lower = []
        lower_info = self.salesman_set.all()
        for lower in lower_info:
            all_lower.append(lower)
            lower_lower_info = lower.salesman_set.all()
            for lower_lower in lower_lower_info:
                all_lower.append(lower_lower)
        return all_lower

    def __str__(self):
        if self.name:
            return self.name
        else:
            return str(self.id)


# class SalesManExtend(models.Model):
#     img = models.ImageField(verbose_name="分享图")
#     salesman = models.OneToOneField("SalesMan", verbose_name="业务员")
#
#     class Meta:
#         verbose_name = "业务员扩展信息"  # admin后台显示
#         verbose_name_plural = verbose_name  # 复数显示


# class SalesProduct(models.Model):
#     sales = models.ForeignKey("SalesMan", verbose_name="业务员")
#     product = models.ForeignKey("product.Product", verbose_name="产品")
#     share_img = models.TextField(verbose_name="单产品分享")
#     create_time = models.DateTimeField(auto_now=True)
#
#     class Meta:
#         verbose_name = "业务员产品关系表"
#         verbose_name_plural = verbose_name


class ApplicantList(models.Model):
    """
    申请人列表
    """
    name = models.CharField(max_length=64, verbose_name="申请人姓名", db_index=True)
    card = models.CharField(max_length=20, verbose_name="身份证号", blank=True, null=True)
    tel = models.CharField(verbose_name="手机号", max_length=16, db_index=True, blank=True, null=True)
    salesman = models.ForeignKey("SalesMan", verbose_name="业务员")
    show_status = models.BooleanField(verbose_name="删除", db_index=True, default=True)
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)

    class Meta:
        verbose_name = "申请人列表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.pk)


class VisitApplicant(models.Model):
    """
    访问id和申请人关系表
    """
    STATUS = ((1, "资料提交中"), (2, "拒件"), (3, "二卡"), (4, "数据更新"))
    visit_id = models.IntegerField(verbose_name="访问id", db_index=True, blank=True, null=True)
    product = models.ForeignKey("product.Product", verbose_name="产品")
    applicant = models.ForeignKey("ApplicantList", verbose_name="申请人列表")
    status = models.IntegerField(verbose_name="状态", db_index=True, default=1, choices=STATUS)
    update_time = models.DateTimeField(verbose_name="更新时间", auto_now=True)

    class Meta:
        verbose_name = "访问id和申请人关系表"
        verbose_name_plural = verbose_name


class Single(models.Model):
    """
    点击产品之后记录关系
    """
    product = models.ForeignKey("product.Product", verbose_name="产品")
    applicant = models.ForeignKey("ApplicantList", verbose_name="申请人", blank=True, null=True)
    # 可以代申请，申请用户可以替其他人申请，谁申请给谁钱。
    b_user = models.ForeignKey("SalesMan", verbose_name="申请用户", related_name="single_b_user_set")
    t_user = models.ForeignKey("SalesMan", verbose_name="推荐用户", related_name="single_t_user_set", blank=True, null=True)
    is_close = models.BooleanField(verbose_name="是否已经结算", default=False)
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)

    class Meta:
        verbose_name = "点击产品记录关系"
        verbose_name_plural = verbose_name


class EnterApplyInfo(models.Model):
    STATUS = ((1, "未审核"), (2, "审核通过"), (3, "审核未通过"))
    buy_cash = models.IntegerField(verbose_name="购买价格", blank=True, null=True)
    product = models.ForeignKey("product.Product", verbose_name="产品")
    single = models.ForeignKey("Single", verbose_name="标记信息")
    city = models.ForeignKey("tools.City", verbose_name="城市", blank=True, null=True)
    age = models.CharField(verbose_name="年龄", max_length=4, blank=True, null=True)
    kilometer = models.IntegerField(verbose_name="车辆公里数", blank=True, null=True)
    car_card = models.CharField(verbose_name="车牌", blank=True, null=True, max_length=16)
    status = models.IntegerField(verbose_name="状态", choices=STATUS, default=1)
    is_close = models.BooleanField(verbose_name="是否已经结算", default=False)
    cash = models.DecimalField(verbose_name="贷款金额", max_digits=10, decimal_places=1, default=0)
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    update_time = models.DateTimeField(verbose_name="更新时间", auto_now=True)

    class Meta:
        verbose_name = "产品录入信息(车抵贷)"  # admin后台显示
        verbose_name_plural = verbose_name  # 复数显示


class BoundRelationManger(models.Manager):
    """
    绑定关系
    """

    def create_relation(self, t_user_id, openid):
        info = self.filter(openid=openid)
        if info.exists():
            pass
        elif SalesMan.objects.get(pk=t_user_id).wx_user and openid == SalesMan.objects.get(pk=t_user_id).wx_user.openid:
            pass
        else:
            self.create(
                t_user_id=t_user_id,
                openid=openid,
            )

    def select_relation(self, openid):
        self.filter(openid=openid)


class BoundRelation(models.Model):
    """
    推荐人和被推荐绑定关系（只限于微信）
    1、微信扫码，记录关系
    2、微信上注册 找到相应的openid 绑定到t_user上（这里需要检查tel是否注册过了，如果注册过了就pass。如果没注册过，就添加上）
    """
    t_user = models.ForeignKey("SalesMan", verbose_name="推荐用户", related_name="bound_relation_t_user_set")
    openid = models.CharField(verbose_name="openid", max_length=128, db_index=True)
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    objects = BoundRelationManger()

    class Meta:
        verbose_name = "微信扫码绑定关系"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.t_user.name


class IssueContent(models.Model):
    """
    内容发布
    """
    title = models.CharField(max_length=128, verbose_name="标题")
    create_time = models.DateTimeField(verbose_name="时间", auto_now_add=True)
    num = models.IntegerField(verbose_name="阅读量", default=0)
    logo = models.FileField(upload_to="news/")

    class Meta:
        verbose_name = "新手必读列表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title


class IssueImg(models.Model):
    content = models.ForeignKey("IssueContent", verbose_name="内容")
    order = models.IntegerField(verbose_name="排序")
    img = models.FileField(verbose_name="图片", upload_to='news/issue/')

    class Meta:
        verbose_name = "资讯页面"
        verbose_name_plural = verbose_name
        ordering = ['order']

    def __str__(self):
        return self.content.title
